ES6 的 export 與 import


Posted by cmtilo on 2021-05-03

舉例1

utils.j檔案中:

export function add(a, b) {
  return a + b
}
export const PI = 3.14

或者

function add(a, b) {
  return a + b
}
const PI = 3.14
export {
  add,
  PI
}

index.js檔案中:

import {add, PI} from '.utils'
console.log((3, 5), PI)

或者

import * as utils from '.utils'
console.log(utils.add(3, 5), utils.PI)
export default

舉例2

utils.j檔案中:

export default function add(a, b) {
  return a + b
}
export const PI = 3.14

index.js檔案中:

import add, {PI} from '.utils'//add就不用加上大括號
console.log(add(3, 5))

或者

import {default as add} from '.utils'
import add from '.utils'//這兩個是一樣的

課程下方老師重點提示Export 有幾種方式:

  • export function add() {},使用 import {add} 引入。
  • export {add},與上面那種一樣。
  • export default function add(),使用 import add引入,不需要加大括號。
  • 如果想要用其他名字,可以用 as 取別名,例如說 export {add as addFunction}
  • 可以用 import * as utils from 'utils' 把全部都 import 進來。

#export #import #ES6







Related Posts

[ Nuxt.js 2.x 系列文章 ] Nuxt.js 目錄結構

[ Nuxt.js 2.x 系列文章 ] Nuxt.js 目錄結構

重新立名檔案或資料夾

重新立名檔案或資料夾

筆記、[BE201] 後端中階:Express

筆記、[BE201] 後端中階:Express


Comments